'use strict';

const Controller = require('egg').Controller;
const svgCaptcha = require('svg-captcha')

class HomeController extends Controller {
  //注册 
  async register() {
    let reqdata = this.ctx.request.body
    if (reqdata.verify.toUpperCase() != this.ctx.session.veriftext.toUpperCase()) {
      this.ctx.body = {
        info: '验证码错误',
        code: 4001
      }
    } else {
      var sql = `SELECT*FROM user WHERE tel="${reqdata.tel}"`
      var sql1 = `SELECT*FROM user WHERE username="${reqdata.username}"`
      var resTel = await this.app.mysql.query(sql)
      var resUsername = await this.app.mysql.query(sql1)
      if (resTel[0]) { //账号被注册
        this.ctx.body = {
          info: '账号已注册',
          code: 4002
        }
      } else if (resUsername[0]) { //昵称已存在
        this.ctx.body = {
          info: '昵称已存在',
          code: 4005
        }
      } else { //添加新用户到数据库里
        var sql2 = `insert into user(username,pwd,tel) values ("${reqdata.username}","${reqdata.pasw}","${reqdata.tel}")`
        await this.app.mysql.query(sql2)
        this.ctx.body = {
          info: '注册成功',
          code: 2001
        }
      }
    }
  }
  //登录
  async login() {
    let reqobj = this.ctx.request.body
    
    console.log(reqobj,1111);
    let reschecktel = await this.ctx.service.home.checktel(reqobj.tel)
    if (!reschecktel[0]) {
      this.ctx.body = {
        info: '该账号未注册',
        code: 4003
      }
    } else {
      let reslogin = await this.ctx.service.home.checkpasw(reqobj)
      if (reslogin[0]) {
        //验证码检测
        if (reqobj.verify.toUpperCase() != this.ctx.session.veriftext.toUpperCase()) {
          this.ctx.body = {
            info: '验证码错误',
            code: 4001
          }
        } else {
          this.ctx.session.id = reslogin[0].id
          this.ctx.body = {
            info: '登录成功',
            code: 2002,
            username: `${reslogin[0].username}`,
          }
        }
      } else {
        this.ctx.body = {
          info: '密码错误',
          code: 4004
        }
      }
    }
  }
  //验证码
  async verify() {
    const captcha = svgCaptcha.create({
      size: 4,
      fontSize: 45,
      width: 100,
      height: 40,
      background: 'azure'
    })
    //将验证码缓存
    this.ctx.session.veriftext = captcha.text
    //将验证码svg字符发给前端显示
    this.ctx.body = captcha.data
  };
}

module.exports = HomeController;